<template>
  <div class="app-container">
    <br>
    <el-tabs v-model="editableTabsValue" type="border-card" 
    @tab-remove="removeTab">
      <el-tab-pane
        label="入库列表"
        name="入库列表"
      >
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        closable
      >
        <el-table-column align="center" label="序号" min-width="30">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="入库单号" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.code }}
          </template>
        </el-table-column>
        <el-table-column label="库名" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.drugDepositoryName }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="入库类型" width="130" align="center">
          <template slot-scope="scope">
            {{ scope.row.type }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="入库部门" width="200" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deptName }}</span>
          </template>
        </el-table-column> -->
        <el-table-column :label="'品类\n数量'" min-width="40" align="center">
          <template slot-scope="scope">
            {{ scope.row.drugTypeNum }}
          </template>
        </el-table-column>
        <el-table-column label="总数量" min-width="41" align="center">
          <template slot-scope="scope">
            {{ scope.row.drugNum }}
          </template>
        </el-table-column>
        <el-table-column label="入库单提交时间" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.createdTime }}
          </template>
        </el-table-column>
        <el-table-column label="审批完成时间" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.status != 0 ? scope.row.updatedTime : '--' }}
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusNameFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="操作" align="center" min-width="300" >
          <template slot-scope="scope">
            <el-button type="primary" :loading="toInfoBtnLoading"  @click="getInfo(scope.row)" size="small">详情</el-button>
            <!-- <el-button type="success" :loading="toUpdateBtnLoading" @click="update(scope.row)" size="small" v-if="scope.row.status === 0">修改</el-button> -->
            <!-- <el-button type="warning" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, true)" size="small">审批</el-button>
            <el-button type="danger" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, false)" size="small">拒绝</el-button> -->
            <!-- <el-button type="info"  @click="toCopy(scope.row)" size="small">复制</el-button> -->
            <!-- <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="->, total, prev, pager, next"
        :total="this.total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="clickCurPage"
        >
      </el-pagination>

      </el-tab-pane>
      <el-tab-pane
        label="入库单"
        name="入库单"
      >
      <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
        <el-row :gutter="10">
          <el-col :span=4 >
            <el-form-item label="入库单号" v-if="form.code != '---'">
                <el-input v-model="form.code" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <!-- <el-col :span=8 >
            <el-form-item label="供货商" prop="supplier">
              <el-select v-model="form.supplier" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in suppliers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span=4 >
            <el-form-item label="库房" prop="dept">
              <el-select v-model="form.drugDepositoryId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in depositoryEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span=4 >
            <el-form-item label="品类数量">
                <el-input v-model="form.drugTypeNum" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span=4 >
            <el-form-item label="总数量">
                <el-input v-model="form.drugNum" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <h3>入库药品</h3>
        <el-form-item label="搜索药品">
          <el-autocomplete
            :disabled="form.drugDepositoryId === undefined"
            value-key="pinyinCode"
            class="inline-input"
            v-model="searchValue"
            :fetch-suggestions="querySearch"
            placeholder="请输入 拼音简码"
            :trigger-on-focus="false"
            @select="(drug)=>handleSelect(drug, form)"
            style="width: 100%;"
          >
          <template slot-scope="{ item }">
            <span >{{ item.code? item.code : '' }}</span>
            <span >{{ item.commonName? '['+item.commonName+'] ' : '' }}</span>
            <span >{{ item.name? item.name+' ' : '' }}</span>
            <span >{{ item.specs? item.specs+' ' : ''  }}</span>
            <span >{{ item.form? item.form+' ' : '' }}</span>
            <span >{{ item.num? '库存:[' +item.num+'] ' : '库存:[0]' }}</span>
            <!-- <span >{{ item.factory? item.factory+' ' : '' }}</span> -->
            <span >{{ item.productTime ? '(' + item.productTime.split('T')[0] + '—' + item.expiration.split('T')[0] + ')' : '' }}</span>
            
          </template>
          </el-autocomplete>
        </el-form-item>

        <!-- 改成table -->
        <el-table
          style="width: 100%;white-space: pre-wrap;"
          :data="form.purchaseOrderDrugList"
          element-loading-text="Loading"
          border
          fit
          :header-cell-style="{ height: '5px', padding: '0 0' }"
        > 
          <el-table-column label="序号" align="center" width="50">
            <template slot-scope="subDrugScope">
              <div>{{ subDrugScope.$index+1 }}</div>
              <el-button class="del-btn" @click="delDrug(subDrugScope.$index, form)" type="danger" icon="el-icon-delete" circle ></el-button> 
            </template>
          </el-table-column>
          <el-table-column :label="'商品名称'" align="center" width="240">
            <template slot-scope="subDrugScope">
              <span>{{ subDrugScope.row.drugCode + '[' +subDrugScope.row.drugCommonName + ']'}}</span><br>
              <span>{{ subDrugScope.row.drugName }}</span><br>
              <span>{{ subDrugScope.row.drugSpecs }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="'厂家'" align="center" width="120" >
            <template slot-scope="subDrugScope">
              {{ subDrugScope.row.factoryName }}
            </template>
          </el-table-column>
          <el-table-column :label="'库存数量'" align="center" width="80" >
            <template slot-scope="subDrugScope">
              {{ subDrugScope.row.sourceNum }}
            </template>
          </el-table-column>
          <el-table-column :label="'批号'" align="center" width="140" >
            <template slot-scope="subDrugScope">
              <el-input class="first-row" size="mini" style="width: 100px;" placeholder="请输入" v-model="subDrugScope.row.batchCode" ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="'生产日期'" align="center" width="150" >
            <template slot-scope="subDrugScope">
              <el-date-picker 
                :picker-options="productTimepickerOptions"
                style="width: 130px" 
                v-model="subDrugScope.row.productTime" 
                size="mini" 
                type="date" 
                placeholder="选择日期" 
                value-format="yyyy-MM-dd" 
                @input="inputProductTime(subDrugScope.row)" >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column :label="'保质期'" align="center" width="150" >
            <template slot-scope="subDrugScope">
              <el-input
                class="first-row"
                size="mini"
                type="Number"
                min=0
                placeholder="请输入"
                v-model="subDrugScope.row.qualityTime"
                @input="inputQualityTime(subDrugScope.row)" >
                <template slot="append">
                  <!-- <span style="font-size: 14px;">{{ subDrugScope.row.isDaysQualityTime ? '日' : '月' }}</span> -->
                  <el-select style="width: 60px;" v-model="subDrugScope.row.isDaysQualityTime" placeholder="请选择" >
                    <el-option
                      label="日"
                      :value="true"
                      @click.native="inputQualityTime(subDrugScope.row)"
                    />
                    <el-option
                      label="月"
                      :value="false"
                      @click.native="inputQualityTime(subDrugScope.row)"
                    />
                  </el-select>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column :label="'有效期至'" align="center" width="150" >
            <template slot-scope="subDrugScope">
              <el-date-picker 
                :picker-options="subDrugScope.row.expirationTimepickerOptions"
                style="width: 130px"
                v-model="subDrugScope.row.expiration"
                size="mini"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                @input="inputExpirationTime(subDrugScope.row)" >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column :label="'入库数量'" align="center" width="150" >
            <template slot-scope="subDrugScope">
              <el-input class="first-row" size="mini" type="Number" min=1 placeholder="请输入" v-model="subDrugScope.row.putNum" @input="inputNum(form)" >
                <template slot="append">
                  <span style="font-size: 14px;">{{ subDrugScope.row.outerUnit }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
          <el-button type="primary" @click="confirm(form)">提交</el-button>
        </div>
      </el-form>
      </el-tab-pane>

      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.id"
        :label="item.title"
        :name="item.name"
        closable
        @tab-remove="removeTab"
      >
        <el-form ref="form1" :model="item" label-width="80px" :rules="formRules">
          <el-row :gutter="10">
            <el-col :span=8 >
              <el-form-item label="入库单号" v-if="form.code != '---'">
                  <el-input v-model="item.content.code" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <!-- <el-col :span=8 >
              <el-form-item label="供货商" prop="supplier">
                <el-select v-model="form.supplier" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in suppliers"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span=4 >
              <el-form-item label="库房" prop="dept">
                <el-select v-model="item.content.drugDepositoryId" placeholder="请选择" style="width: 100%" :disabled="true" >
                  <el-option
                    v-for="item in depositoryEnum"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span=4 >
              <el-form-item label="品类数量">
                  <el-input v-model="item.content.drugTypeNum" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span=4 >
              <el-form-item label="总数量">
                  <el-input v-model="item.content.drugNum" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <h3>入库药品</h3>
          <el-form-item label="搜索药品">
            <el-autocomplete
              :disabled="true"
              value-key="pinyinCode"
              class="inline-input"
              v-model="item.content.searchValue"
              :fetch-suggestions="querySearch"
              placeholder="请输入 拼音简码"
              :trigger-on-focus="false"
              @select="(drug) => handleSelect(drug, item.content)"
              style="width: 100%;"
            >
            <template slot-scope="{ searchItem }">
              <span >{{ searchItem.name+'/' }}</span>
              <span >{{ searchItem.commonName+' ' }}</span>
              <span >{{ searchItem.form+' ' }}</span>
              <span >{{ searchItem.specs+' '  }}</span>
              <span >{{ searchItem.factory }}</span>
            </template>
            </el-autocomplete>
          </el-form-item>

          <!-- 改成table -->
          <el-table
            style="width: 100%;white-space: pre-wrap;"
            :data="item.content.purchaseOrderDrugList"
            element-loading-text="Loading"
            border
            fit
            :header-cell-style="{ height: '10px', padding: '0 0' }"
          > 
            <el-table-column label="序号" align="center" width="50">
              <template slot-scope="subDrugScope">
                <div>{{ subDrugScope.$index+1 }}</div>
              </template>
            </el-table-column>
            <el-table-column :label="'商品名称'" align="center" width="240">
              <template slot-scope="subDrugScope">
                <span>{{ subDrugScope.row.drugCode + '[' +subDrugScope.row.drugCommonName + ']'}}</span><br>
                <span>{{ subDrugScope.row.drugName }}</span><br>
                <span>{{ subDrugScope.row.drugSpecs }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'厂家'" align="center" width="120" >
              <template slot-scope="subDrugScope">
                {{ subDrugScope.row.factoryName }}
              </template>
            </el-table-column>
            <el-table-column :label="'库存数量'" align="center" width="80" >
              <template slot-scope="subDrugScope">
                {{ subDrugScope.row.sourceNum }}
              </template>
            </el-table-column>
            <el-table-column :label="'批号'" align="center" width="140" >
              <template slot-scope="subDrugScope">
                <el-input class="first-row" size="mini" style="width: 100px;" placeholder="请输入" v-model="subDrugScope.row.batchCode" :disabled="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column :label="'生产日期'" align="center" width="150" >
              <template slot-scope="subDrugScope">
                <el-date-picker
                  :disabled="true"
                  :picker-options="productTimepickerOptions"
                  style="width: 130px" 
                  v-model="subDrugScope.row.productTime" 
                  size="mini" 
                  type="date" 
                  placeholder="选择日期" 
                  value-format="yyyy-MM-dd" 
                   >
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column :label="'保质期'" align="center" width="150" >
              <template slot-scope="subDrugScope">
                <el-input
                  :disabled="true"
                  class="first-row"
                  size="mini"
                  type="Number"
                  min=0
                  placeholder="请输入"
                  v-model="subDrugScope.row.qualityTime"
                   >
                   <template slot="append">
                      <span style="font-size: 14px;">{{ subDrugScope.row.isDaysQualityTime ? '日' : '月' }}</span>
                    </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="'有效期至'" align="center" width="150" >
              <template slot-scope="subDrugScope">
                <el-date-picker 
                  :disabled="true"
                  :picker-options="subDrugScope.row.expirationTimepickerOptions"
                  style="width: 130px"
                  v-model="subDrugScope.row.expiration"
                  size="mini"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                   >
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column :label="'入库数量'" align="center" width="100" >
              <template slot-scope="subDrugScope">
                <el-input class="first-row" size="mini" type="Number" min=1 placeholder="请输入" v-model="subDrugScope.row.putNum" :disabled="true" ></el-input>
              </template>
            </el-table-column>
            
            <el-table-column :label="'审批操作'" align="center" width="150" >
              <template slot-scope="subDrugScope">
                <el-popover
                  v-model="subDrugScope.row.visible"
                  v-if = "item.content.isCostPrice"
                  placement="right"
                  width="350"
                  trigger="click"
                  >
                  <div class="drugs-item" 
                  >
                    <span class="drugs-item-title" style="width: 300px;">供应商</span>
                    <el-select v-model="subDrugScope.row.supplier" filterable placeholder="请选择" style="width: 300px;" :disabled="subDrugScope.row.status==1?true:false">
                      <el-option
                        v-for="item in suppliers"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </div>
                  <br>
                  <div class="drugs-item" >
                    <span class="drugs-item-title" style="width: 300px;">进价(元)</span>
                    <el-input class="drug-input" type="Number" min=0 v-model="subDrugScope.row.costPrice" :disabled="subDrugScope.row.status==1"></el-input>
                  </div>
                  <br>
                  <br>
                  <el-button type="primary" @click="godownCostPrice(subDrugScope.row, item.content)" size="small" :disabled="subDrugScope.row.status==1">{{subDrugScope.row.status==1 ? '已入库' : '审批入库'}}</el-button>
                  <el-button @click="subDrugScope.row.visible = false" size="small" >取消</el-button>
                  
                  <el-button slot="reference" >{{subDrugScope.row.status == 1 ? '已入库' : '审批入库'}}</el-button>
                </el-popover>
              </template>
            </el-table-column>
            
          </el-table>
        </el-form>
      </el-tab-pane>
    </el-tabs>


  </div>
</template>

<script>
import { getListByPinyinCode, queryByCodeAnDepositoryId } from '@/api/drug'
import { godownDrug, godownCostPrice, getList, getListInfo as getInfo} from '@/api/godown'
import { getList as getSupplierList } from '@/api/supplier'
import { getAvailableDepositoryList } from '@/api/store'
import { stringToDate, addDate, subDate, betweenDate } from '@/utils/dateUtil'
import { audit, getList as getAuditList, getInfo as getAuditInfo } from '@/api/auditFlow'
import drugDepositoryAuthVue from './drugDepositoryAuth.vue'

export default {
  name: "Input",
  filters: {
    // statusColorFilter(status) {
    //   const statusMap = ['success', 'warning', 'primary', 'danger']
    //   return statusMap[status]
    // },
    // statusNameFilter(status) {
    //   const statusMap = ['草稿', '待审批', '审批完成', '已拒绝']
    //   return statusMap[status]
    // }
    statusColorFilter(status) {
      const statusMap = ['success', 'primary']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['待审批', '已入库']
      return statusMap[status]
    }
  },
  data() {
    const validatePlan = (rule, value, callback) => {
      if (!value) callback(new Error('请填写计划名称')) 
      else callback()
    }
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型'))
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!this.form.drugDepositoryId) callback(new Error('请选择库'))
      else callback()
    }
    const validateSupplier = (rule, value, callback) => {
      if (!this.form.supplier) callback(new Error('请选择供货商'))
      else callback()
    }
    const validateAuditPreset = (rule, value, callback) => {
      for (let index = 0; index < this.auditPreset.length; index++) {
        if(!this.auditPreset[index].auditUser) callback(new Error('请选择审批人'))
      }
      callback()
    }
    return {
      list: null,
      listLoading: true,
      toUpdateBtnLoading: false,
      toInfoBtnLoading: false,
      commitBtnLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      dialogTitle: '',
      info: {},
      form: {drugTypeNum: 0, drugNum: 0, purchaseOrderDrugList: []},
      purchaseOrderDrugList: [],
      typeEnum: ["集中", "临时"],
      depositoryEnum: [],
      suppliers: [],
      query: {},
      tagEnum: [{id: 1, name: '热销'},{id: 2, name: '促销'}],
      dugTypeTreeList: [],
      formRules: {
        plan: [{ required: true, trigger: 'blur', validator: validatePlan }],
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
        supplier: [{ required: true, trigger: 'blur', validator: validateSupplier }],
        auditPreset: [{ required: true, trigger: 'blur', validator: validateAuditPreset }],
      },
      searchValue: '',
      isCostPrice: false,
      auditPreset: [],
      editableTabsValue: '入库列表',
      editableTabs: [],
      productTimepickerOptions: {
        disabledDate: time => {
          return (
            //new Date(this.timeDate.endTime).getTime()<= time.getTime() 
            time.getTime() >= new Date().getTime()
          );
        }
      },
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.initList()
      getSupplierList().then(supplierRes => {
        console.log(supplierRes)
        this.suppliers = supplierRes.data
      })
      getAuditInfo({businessCode: 'purchase_order'}).then(res=> {
        this.auditPreset = res.data
      })
      getAvailableDepositoryList({optType: 3}).then(deptRes=> {
        console.log("deptRes", deptRes)
        this.depositoryEnum = deptRes.data
      })
    },
    initList() {
      this.listLoading = true
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          type: '临时'
      }
      getList(reqBody).then(response => {
        console.log(response)
        this.list = response.data.records
        if(this.list && this.list.length != 0) {
          this.list.forEach(item=>{
            if(item.auditStatus != undefined) {
              item.status = item.auditStatus
            }
          })
        }
        this.total = response.data.total
        this.listLoading = false
        
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    async getInfo(row) {
      if(this.editableTabs.map(tab => tab.name).includes(row.code)) {
        this.editableTabsValue = row.code
        return
      }
      const infoRes = await getInfo({code: row.code})
      console.log('infoRes', infoRes)
      // 
      const deptRes = await getAvailableDepositoryList({optType: 8})
      if(deptRes.data.map(drugDepository => drugDepository.id).includes(row.drugDepositoryId)) {
        this.$set(row, 'isCostPrice', true)
      }
      this.$set(row, 'purchaseOrderDrugList', infoRes.data)
      this.$set(row, 'searchValue', '')
      this.$set(row, 'inputNum', undefined)
      this.$set(row, 'drugDepositoryId', row.drugDepositoryId)
      this.editableTabs.push({
        title: row.code,
        name: row.code,
        content: row,
      })
      this.editableTabsValue = row.code
      console.log('row', row)
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改入库单'
      this.toUpdateBtnLoading = true
      getInfo(row.id).then(infoRes=>{
        console.log(infoRes)
        this.form = JSON.parse(JSON.stringify(infoRes.data))
        this.auditPreset = infoRes.data.auditFlowDetail.jobDutyList
        this.toUpdateBtnLoading = false
        this.calculateExpirationTime(this.form)
        if(!this.form.operationList) this.$set(this.form, 'operationList', [])
        this.formVisible = true
      })
    },
    toCopy(row) {
      getInfo(row.id).then(infoRes=>{
        console.log(infoRes)
        this.form = JSON.parse(JSON.stringify(infoRes.data))
        this.form.id = undefined
        this.form.status = 0
        this.form.purchaseOrderDrugList.forEach(purchase=>{
          purchase.godownDrugList = []
        })
        this.toUpdateBtnLoading = false
        this.calculateExpirationTime(this.form)
        if(!this.form.operationList) this.$set(this.form, 'operationList', [])
        this.formVisible = true
      })
    },
    calculateExpirationTime(form) {
      form.purchaseOrderDrugList.forEach(drugItem=> {
        drugItem.godownDrugList.forEach(godown=> {
          if(godown.productTime != undefined) {
            var productTime = stringToDate(godown.productTime)
            var productYear = productTime.getFullYear();
            var productMonth = productTime.getMonth();
            var expiration = stringToDate(godown.expiration)
            var expirationYear = expiration.getFullYear();
            var expirationMonth = expiration.getMonth();
            this.$set(godown, 'qualityTime', expirationMonth - productMonth + (expirationYear - productYear)*12)
          }
        })
      })
    },
    deleteInfo(scope) {
      this.$confirm('确定删除该职务?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    confirm(purchase) {
      this.commitBtnLoading = true
      purchase.auditUserIds = this.auditPreset.map(jobDutyVo => Number(jobDutyVo.auditUser))
      purchase.source = "采购"
      if(!this.checkInputForm(purchase)) return
      var goDownDrugBOList = []
      for (const godownItem of purchase.purchaseOrderDrugList) {
        var inputDrug = {
          drugCode: godownItem.drugCode,
          sourceNum: godownItem.sourceNum,
          batchCode: godownItem.batchCode,
          // num: Number(godownItem.godownNum),
          num: Number(godownItem.putNum),
          productTime: godownItem.productTime,
          qualityTime: godownItem.qualityTime,
          expiration: godownItem.expiration,
        }
        goDownDrugBOList.push(inputDrug)
      }
      purchase.goDownDrugBOList = goDownDrugBOList
      console.log("form", purchase)
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          purchase.status = 1
          godownDrug(purchase).then(res=>{
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.commitBtnLoading = false
            this.formVisible = false
            this.listLoading = false
            this.$tab.refreshPage({path: '/store/input', name: "Input"});
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          this.commitBtnLoading = false
          return false
        }
      })
    },
    checkInputForm(form) {
      if(!this.form.drugDepositoryId) {
        this.$alert('未选择库房', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      if(!this.form.purchaseOrderDrugList || this.form.purchaseOrderDrugList.length == 0) {
        this.$alert('未选择商品', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      for (const godownItem of this.form.purchaseOrderDrugList) {
        var drugInfo = godownItem.drugCode + ' [' + godownItem.drugCommonName + '] '
        if(!godownItem.batchCode) {
          this.$alert(drugInfo + '未填写生产批号', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        }
        if(!godownItem.putNum) {
          this.$alert(drugInfo + '未填写库存', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        }
        if(!godownItem.productTime) {
          this.$alert(drugInfo + '未选择生产日期', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        }
        if(!godownItem.qualityTime) {
          this.$alert(drugInfo + '未填写保质期', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        }
        if(!godownItem.expiration) {
          this.$alert(drugInfo + '未选择有效期日期', '错误', {
            confirmButtonText: '确定',
            type: 'error',
          });
          return false
        }
      }
      return true
    },
    cancel() {
      this.infoVisible = false
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    querySearch(queryString, cb) {
      getListByPinyinCode(queryString, [this.form.drugDepositoryId]).then(drugListRes=>{
        // 调用 callback 返回建议列表的数据
        cb(drugListRes.data);
      })
    },
    handleSelect(item, purchase) {
      // if(this.form.purchaseOrderDrugList.map(drugItem => drugItem.drugCode).indexOf(item.code) != -1) {
      //   this.$message.error('药品已存在');
      //   return;
      // }
      this.searchValue = item.name + '/' + item.commonName + ' ' + item.form + ' ' + item.specs + ' ' + item.factory
      console.log('item', item)
      console.log('purchase', purchase)
      queryByCodeAnDepositoryId({drugCode: item.code, depositoryId: purchase.drugDepositoryId}).then(res=> {
      console.log("res", res)
        var purchaseOrder = {
          drugCode: item.code,
          drugName: item.name,
          drugCommonName: item.commonName,
          drugSpecs: item.specs,
          status: item.status,
          factory: item.factory,
          factoryName: item.factoryName,
          form: item.form,
          outerUnit: item.outerUnit,
          num: 0,
          minPurchaseNum: item.minPurchaseNum,
          buyCycle: item.buyCycle,
          depositoryId: purchase.drugDepositoryId,
          depositoryName: this.getDepositoryName(purchase.drugDepositoryId),
          godownDrugList: [{
            drugCode: item.code,
            drugCommonName: item.commonName,
            num: 0,
            expiration: undefined,
            productTime: undefined,
          }],
          isDaysQualityTime: false,
          drugDepositoryVoList: [{
            id: this.form.drugDepositoryId,
            name: this.getDepositoryName(purchase.drugDepositoryId), 
            sourceNum: res.data ? res.data.inventory : 0,
            doneInventory: res.data ? res.data.inventory : 0,
          }],
          putNum: 0,
          sourceNum: res.data ? res.data.inventory : 0,
        }
        this.$set(purchaseOrder, 'operationList', [{
          drugCode: item.code,
          num: 0,
          operationType: 2,
          targetDepositoryId: purchase.drugDepositoryId,
        }])
        purchaseOrder.sourceNum = res.data ? res.data.inventory : 0,
        purchase.purchaseOrderDrugList.push(purchaseOrder)
        console.log(purchase.purchaseOrderDrugList)
        purchase.drugTypeNum++
        this.searchValue = ''
      })
    },
    delDrug(index, purchase) {
      let list = purchase.purchaseOrderDrugList
      let drug = list[index]

      this.$confirm('删除 '+ drug.drugCode + ' ' + drug.drugCommonName +', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        list.splice(index, 1)
        purchase.drugTypeNum--
        purchase.drugNum = list.reduce((sum, obj) => Number(sum) + Number(obj.putNum), 0);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });

    },
    inputNum(purchase) {
      let drugNum = this.form.purchaseOrderDrugList.reduce((sum, obj) => Number(sum) + Number(obj.putNum), 0);
      console.log('drugNum', drugNum)
      this.$set(purchase, 'drugNum', drugNum)
      console.log(purchase.purchaseOrderDrugList)
    },
    approve(row, pass) {
      console.log(row)
      this.toUpdateBtnLoading = true
      audit({flowNo: row.code, pass: pass}).then(auditRes=> {
        console.log("auditRes", auditRes)
        this.toUpdateBtnLoading = false
        this.fetchData()
      })
    },
    checkMin(opt, drug) {
      if(opt.putNum < drug.minPurchaseNum) {
        this.$message.error('低于最低采购量,已自动计算');
        opt.putNum = drug.minPurchaseNum
        this.form.drugNum = this.form.purchaseOrderDrugList.reduce((sum, obj) => Number(sum) + Number(obj.putNum), 0);
      }
    },
    getDepositoryName(id) {
      return this.depositoryEnum.filter(dep => dep.id === id)[0].name
    },
    inputProductTime(godown) {
      // 删除生产日期
      if(!godown.productTime) {
        this.$set(godown, 'productTime', undefined)
        this.$set(godown, 'qualityTime', undefined)
        this.$set(godown, 'expiration', undefined)
        this.$set(godown, 'isDaysQualityTime', false)
        return
      }
      godown.productTime = new Date(godown.productTime)
      godown.expirationTimepickerOptions = {
        disabledDate: time => {
          return (
            //new Date(this.timeDate.endTime).getTime()<= time.getTime() 
            time.getTime() < godown.productTime.getTime()
          );
        }
      }
      if (godown.qualityTime) {
        var expiration = addDate(godown.productTime, 'month', godown.qualityTime)
        var finalExpirationTime = subDate(expiration, 'day', 1)
        this.$set(godown, 'expiration', finalExpirationTime)
      } else if (godown.expiration) {
        var betweenMonth = betweenDate(godown.productTime, godown.expiration, 'month')
        this.$set(godown, 'qualityTime', betweenMonth)
      }
    },
    inputQualityTime(godown) {
      // 删除有效期
      if(!godown.qualityTime) {
        this.$set(godown, 'expiration', undefined)
        this.$set(godown, 'isDaysQualityTime', false)
        return
      }
      if(godown.isDaysQualityTime && godown.qualityTime > 30) {
        this.$set(godown, 'isDaysQualityTime', false)
        this.$set(godown, 'qualityTime', godown.qualityTime - 30)
      }
      if(godown.productTime) {
        var expiration = addDate(godown.productTime, 'month', godown.qualityTime)
        // 保质期是否按天 
        if(godown.isDaysQualityTime) {
          expiration = addDate(godown.productTime, 'day', godown.qualityTime)
        }
        var finalExpirationTime = subDate(expiration, 'day', 1)
        this.$set(godown, 'expiration', finalExpirationTime)
      } else if (godown.expiration) {
        var productTime = subDate(godown.expiration, 'month', godown.qualityTime)
        // 保质期是否按天 
        if(godown.isDaysQualityTime) {
          productTime = subDate(godown.expiration, 'day', godown.qualityTime)
        }
        var finalProductTime = addDate(productTime, 'day', 1)
        this.$set(godown, 'productTime', finalProductTime)
      }
    },
    inputExpirationTime(godown) {
      // 删除失效日期
      if(!godown.expiration) {
        this.$set(godown, 'qualityTime', undefined)
        this.$set(godown, 'isDaysQualityTime', false)
        return
      }
      godown.expiration = new Date(godown.expiration)
      if(godown.productTime) {
        var betweenMonth = betweenDate(godown.productTime, godown.expiration, 'month')
        this.$set(godown, 'qualityTime', betweenMonth)
        // 计算小于30天
        var betweenDays = betweenDate(godown.productTime, godown.expiration, 'day')
        this.$set(godown, 'isDaysQualityTime', false)
        if(betweenDays < 30) {
          this.$set(godown, 'isDaysQualityTime', true)
          this.$set(godown, 'qualityTime', betweenDays+Number(1))
        }
        console.log('godown.qualityTime', godown.qualityTime)
      } else if (godown.qualityTime) {
        var productTime = subDate(godown.expiration, 'month', godown.qualityTime)
        var finalProductTime = addDate(productTime, 'day', 1)
        this.$set(godown, 'productTime', finalProductTime)
      }
    },
    inputGodownNum(opt, godown) {
      var sumGodownNum = 0
      // if(opt.godownDrugList) sumGodownNum = opt.godownDrugList.filter(drug => drug.id != undefined).reduce((sum, obj) => Number(sum) + Number(obj.godownNum), 0);
      if(Number(sumGodownNum) + Number(godown.godownNum) > opt.putNum) {
        this.$message.error('超过采购数量，已自动计算')
        this.$set(godown, 'godownNum', opt.putNum - sumGodownNum)
      }
    },
    checkGoDownNum() {
      this.form.purchaseOrderDrugList.forEach(purchaseOrder=>{
        purchaseOrder.operationList.forEach(optItem=> {
          optItem.godownDrugList.forEach(godownDrug=>{
            if(godownDrug.batchCode == undefined || godownDrug.batchCode == '') {
              this.$message.error('请填写批号')
              throw new Error('请填写批号')
            } else if(godownDrug.productTime == undefined) {
              this.$message.error('请填写生产日期')
              throw new Error('请填写生产日期')
            } else if(godownDrug.expiration == undefined) {
              this.$message.error('请填写过期时间')
              throw new Error('请填写过期时间')
            } else if(godownDrug.godownNum == undefined || Number(godownDrug.godownNum) <= 0) {
              this.$message.error('请填写入库数量')
              throw new Error('请填写入库数量')
            }
          })
        })
      })
    },
    godownCostPrice(drug, purchase) {
      if(!drug.supplier) {
        this.$alert('未选择供货商', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return
      }
      if(!drug.costPrice) {
        this.$alert('未填写成本价格', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return
      }
      godownCostPrice(drug).then(res=> {
        drug.status = 1
        drug.visible = false
        this.$message.success('入库成功')
        let finishAll = true
        for (const element of purchase.purchaseOrderDrugList) {
          if(element.status != 1) { // 有1个没填的，就是未完成
            finishAll = false
            break
          }
        }
        if(finishAll) {
          // 都完成 刷新列表
          this.initList()
        }
        console.log(res)
      })
    },
    
    removeTab(targetName) {
      console.log(targetName)
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      if(this.editableTabs.length == 0) this.editableTabsValue = '入库列表'
    },

  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .drug-input {
    width: 300px;
    display: inline-block;
    margin-right: 10px;
  }
  .drugs-item-title {
    line-height: 20px;
    text-align: center;
    background-color: #E4E7ED;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .drugs-item {
    width: 140px;
    display: flex;
    flex-direction: column;
    margin-right: 10px;
  }
  .drug-name {
    width: 400px;
    word-wrap: break-word;
    margin-right: 20px;
    font-size: 14px;
    height: 58px;
    line-height: 58px;
    display: flex;
    justify-content: center;
  }
  .drug-name-info {
    width: 300px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-right: 20px;
    padding: 0;

  }
  .drug-name-factory {
    width: 450px;

  }
  .drug-name-info > span{
    display: inline-block;
    height: 20px;
  }
  .del-btn {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 4px;
  }
  ::v-deep .el-input-group__append {
    padding: 0 5px;
  }


</style>